package com.tools.generator.config;

import cn.hutool.core.util.StrUtil;
import com.tools.common.utils.Asserts;
import com.tools.generator.entity.DataSourceEntity;
import com.tools.generator.enums.dbEnum;
import com.tools.generator.query.AbstractQuery;
import com.tools.generator.query.MySQLQuery;
import com.tools.generator.query.SQLiteQuery;
import com.tools.generator.utils.DbUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据源信息
 *
 * @author Admin
 */
@Slf4j
@Data
public class ToolDataSource {

    /**
     * 数据源ID
     */
    private Long id;
    /**
     * 数据库类型
     */
    private dbEnum dbType;
    /**
     * 数据库URL
     */
    private String connUrl;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;

    /**
     * 抽象查询对象
     */
    private AbstractQuery dbQuery;

    /**
     * 连接对象
     */
    private Connection connection;

    /**
     * 构造方法 封装连接
     *
     * @param connect 前端传递的连接对象
     */
    public ToolDataSource(DataSourceEntity connect) {
        this.id = connect.getId();
        this.connUrl = connect.getConnUrl();
        this.username = connect.getUserName();
        this.password = connect.getUserPwd();
        this.dbType = dbEnum.getValue(connect.getDbType());
        switch (dbType) {
            case MySQL:
                this.dbQuery = new MySQLQuery();
                break;
            case SQLite:
                this.dbQuery = new SQLiteQuery();
                break;
            default:
                break;
        }
        try {
            this.connection = DbUtils.getConnection(this);
        } catch (Exception e) {
            log.error("连接出现异常:{}", e.getMessage());
            log.error("连接地址为:{}",connUrl);
            Asserts.isTrue(true, StrUtil.format("异常信息：{}",e.getMessage()));
        }
    }

    public ToolDataSource(Connection connection) throws SQLException {
        this.id = 0L;
        this.dbType = dbEnum.getValue(connection.getMetaData().getDatabaseProductName());
        log.info("数据库类型：{}",dbType);
        switch (dbType) {
            case MySQL:
                this.dbQuery = new MySQLQuery();
                break;
            case SQLite:
                this.dbQuery = new SQLiteQuery();
                break;
            default:
                break;
        }
        this.connection = connection;
    }
}
